<template>
  <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="0">
    <el-form-item prop="username">
      <el-input
        v-model="form.username"
        size="large"
        style="height: 46px"
        placeholder="请输入用户名"
        :prefix-icon="User"
      />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="form.password"
        size="large"
        style="height: 46px"
        placeholder="请输入密码"
        show-password
        :prefix-icon="Lock"
      />
    </el-form-item>
    <el-form-item prop="captchacode">
      <el-input
        v-model="form.captchacode"
        placeholder="请输入验证码"
        style="height: 46px"
        :prefix-icon="CircleCheck"
      >
        <template #append>
          <img
            class="h-[40px] w-[72px] cursor-pointer"
            :src="captchaSrc"
            alt="Base64 Image"
            @click="refreshCaptcha"
          />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        class="w-[100%] mt-[5px]"
        type="primary"
        size="large"
        @click="handleLogin(ruleFormRef)"
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import pinia from '@/store';
  import { useRouter } from 'vue-router';
  import { useUserInfo } from '@/store/user';
  import { useAuthApi } from '@/api/auth';
  import { setAddRoute } from '@/router';
  import { ElNotification } from 'element-plus';
  import { User, Lock, CircleCheck } from '@element-plus/icons-vue';
  import type { ComponentSize, FormInstance, FormRules } from 'element-plus';

  const router = useRouter();
  const authApi = useAuthApi();

  const captchaSrc = ref('');
  const sessionId = ref<String>('');
  const isLogin = ref<Boolean>(false);
  const ruleFormRef = ref<FormInstance>();

  const form = reactive({
    username: '',
    password: '',
    captchacode: '',
  });

  const rules = reactive<FormRules<any>>({
    username: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      },
    ],
    captchacode: [
      {
        required: true,
        message: '请输入验证码',
        trigger: 'blur',
      },
    ],
  });

  const refreshCaptcha = async () => {
    const response = await authApi.captcha();
    const { img, session_id } = response.data;
    captchaSrc.value = `data:image/png;base64,${img}`;
    sessionId.value = session_id;
  };

  const handleLogin = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;

    await formEl.validate(async (valid, fields) => {
      if (valid) {
        let params = {
          session_id: sessionId.value,
          captcha_code: form.captchacode,
        };

        let formData = new FormData();
        formData.append('username', form.username);
        formData.append('password', form.password);
        formData.append('captcha_code', form.captchacode);
        const response = await authApi.login(params, formData);

        const { access_token, user_id } = response.data;
        await updatePermissons(user_id, access_token);
      } else {
        console.log('error submit!', fields);
      }
    });
  };

  const updatePermissons = async (user_id: string, token: string) => {
    const response = await authApi.permissions(user_id);
    console.log(response);

    const userInfo = useUserInfo(pinia);
    userInfo.setUserInfo(response.data, token);
    setAddRoute();
    // isLogin.value = true;

    router.push({ path: '/system' });

    ElNotification({
      title: '登录成果',
      message: `欢迎回来 ${form.username}`,
      type: 'success',
    });
  };

  onMounted(() => refreshCaptcha());
</script>

<style scoped>
  :deep(.el-input-group__append) {
    padding: 0 5px !important;
  }
</style>
